package com.ihighest.app.infox.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.amlcurran.showcaseview.OnShowcaseEventListener;
import com.github.amlcurran.showcaseview.ShowcaseView;
import com.github.amlcurran.showcaseview.targets.ViewTarget;
import com.ihighest.app.common.core.Application;
import com.ihighest.app.common.kit.ScreenKit;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;

import com.ihighest.app.infox.adapter.NewsFragmentPagerAdapter;
import com.ihighest.app.infox.bean.ChannelItem;
import com.ihighest.app.infox.bean.ChannelManage;
import com.ihighest.app.infox.fragment.CopyOfNewsFragment;
import com.ihighest.app.infox.fragment.SubscriptionFragment;
import com.ihighest.app.infox.myview.ActivityTitle;
import com.ihighest.app.infox.myview.ColumnHorizontalScrollView;

/**
 * 资讯界面
 * 
 * @author lkx Created at 2015-10-2 下午3:43:01
 * @version 1.0
 */
public class InformationActivity extends FragmentActivity implements OnShowcaseEventListener {
	final String TAG = "InformationActivity";
	public ActivityTitle title;
	/** 自定义HorizontalScrollView */
	private ColumnHorizontalScrollView mColumnHorizontalScrollView;
	public static LinearLayout mRadioGroup_content;
	LinearLayout ll_more_columns;
	RelativeLayout rl_column;
	private ViewPager mViewPager;
	private ArrayList<Fragment> fragments = new ArrayList<Fragment>();
	private ImageView button_more_columns;
	/** 用户选择的新闻分类列表 */
	private ArrayList<ChannelItem> userChannelList = new ArrayList<ChannelItem>();
	/** 当前选中的栏目 */
	private int columnSelectIndex = 0;
	/** 左阴影部分 */
	public ImageView shade_left;
	/** 右阴影部分 */
	public ImageView shade_right;
	/** 屏幕宽度 */
	private int mScreenWidth = 0;
	/** Item宽度 */
	ImageView askQuestion;
	private long exitTime = 0;// 点击退出键的时间

	/** 请求CODE */
	public final static int CHANNELREQUEST = 1;

	private DataChangeBroadcast receiveBroadCast;// 广播接收
	private ChangeBroadcast changeBroadcast;

	int tag = 1;// 是否从登录返回2代表是

	int step = 1;
	ShowcaseView sv;

	private FragmentManager fm;
	private NewsFragmentPagerAdapter mAdapetr;

	// private CopyOfNewsFragmentPagerAdapter mAdapetr;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Application.getInstance().addActivity(this);
		mScreenWidth = ScreenKit.getScreenWidth(this);
		setContentView(R.layout.infox_activity_information);
		askQuestion = (ImageView) findViewById(R.id.toAskQuestion);
		title = (ActivityTitle) findViewById(R.id.infox_onrTitle);
		title.setTitle("资讯");
		title.setViewVersible(title.rightLayout, title.titleMsg);
		title.setViewGone(title.titleSetting, title.titleRefresh, title.titleOther);
		// 注册广播接收
		receiveBroadCast = new DataChangeBroadcast();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Const.DATACHANGE);
		registerReceiver(receiveBroadCast, filter);

		changeBroadcast = new ChangeBroadcast();
		IntentFilter filter1 = new IntentFilter();
		filter1.addAction(Const.CHANGECOUNT);
		registerReceiver(changeBroadcast, filter1);

		initColumnData();

		initView();

	}

	@SuppressWarnings("deprecation")
	private void intoGuide(int id) {
		try {
			RelativeLayout.LayoutParams lps = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);
			lps.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
			lps.addRule(RelativeLayout.CENTER_HORIZONTAL);
			int margin = ((Number) (getResources().getDisplayMetrics().density * 12)).intValue();
			lps.setMargins(margin, margin, margin, margin);
			if (step == 1) {

				ViewTarget target = new ViewTarget(id, this);
				sv = new ShowcaseView.Builder(this).withMaterialShowcase().setStyle(R.style.CustomShowcaseTheme).setTarget(target)
						.setContentTitle("推荐更懂你").setContentText("您关注的资讯都会在这里为您一一推荐出来").setShowcaseEventListener(this).build();
				sv.setButtonPosition(lps);
			} else if (step == 2) {

				ViewTarget target = new ViewTarget(R.id.mViewPager, this);
				// sv = new
				// ShowcaseView.Builder(this).withMaterialShowcase().setStyle(R.style.CustomShowcaseTheme).setTarget(target)
				// .setContentTitle("加载更多").setContentText("上下滑动手指为您加载更多数据").setShowcaseEventListener(this).build();
				// sv = new
				// ShowcaseView.Builder(this).withMaterialShowcase().setStyle(R.style.CustomShowcaseTheme)
				// .setContentTitle("加载更多").setContentText("上下滑动手指为您加载更多数据").setShowcaseEventListener(this).build();
				sv = new ShowcaseView.Builder(this).withMaterialShowcase().setStyle(R.style.Custom_semi_transparent_demo)
						.setContentTitle("加载更多").setContentText("上下滑动手指为您加载更多数据").setShowcaseEventListener(this).build();
				sv.setBackgroundDrawable(getResources().getDrawable(R.drawable.infox_helptwo));
				sv.setButtonPosition(lps);
			} else if (step == 3) {
				ViewTarget target = new ViewTarget(R.id.toAskQuestion, this);
				sv = new ShowcaseView.Builder(this).withMaterialShowcase().setStyle(R.style.CustomShowcaseTheme).setTarget(target)
						.setContentTitle("想问农技，就戳我").setContentText("这里汇聚农业相关的各类专家，让你一问就应！").setShowcaseEventListener(this).build();
				sv.setButtonPosition(lps);

			} else if (step == 4) {
				ViewTarget target = new ViewTarget(R.id.ll_more_columns, this);
				sv = new ShowcaseView.Builder(this).withMaterialShowcase().setStyle(R.style.CustomShowcaseTheme).setTarget(target)
						.setContentTitle("订阅你需要的").setContentText("在这里可以添加更多你关注的频道").setShowcaseEventListener(this).build();
				sv.setButtonPosition(lps);
				Const.INTO_GUIDE = false;
			}
		} catch (Exception ex) {
			Log.e(TAG, ex.getMessage(), ex);
			Const.INTO_GUIDE = false;
		}

	}

	@Override
	public void onResume() {
		// userChannelList = ((ArrayList<ChannelItem>)
		// ChannelManage.getManage(Application.getInstance().getSQLHelper()).getUserChannel());

		// mViewPager.setCurrentItem(0);
		// setChangelView();
		Log.e("", "进入资讯");
		if (Const.UNREADMESSAGE != 0) {
			title.messagenumber.setText(Const.UNREADMESSAGE + "");
			title.messagenumber.setVisibility(View.VISIBLE);
		} else {
			title.messagenumber.setVisibility(View.GONE);
		}
		// setChangelView();
		super.onResume();
	}

	public class DataChangeBroadcast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// 得到数据变化的广播

			if (intent.getAction().equals(Const.DATACHANGE)) {
				System.out.println("栏目变化");
				setChangelView();
			}

		}

	}

	/**
	 * 绑定控件
	 * 
	 * 
	 * @author lkx Created at 2015-10-3 下午7:14:14
	 */
	private void initView() {
		mColumnHorizontalScrollView = (ColumnHorizontalScrollView) findViewById(R.id.mColumnHorizontalScrollView);
		mRadioGroup_content = (LinearLayout) findViewById(R.id.mLableGroup);
		ll_more_columns = (LinearLayout) findViewById(R.id.ll_more_columns);
		rl_column = (RelativeLayout) findViewById(R.id.rl_column);
		button_more_columns = (ImageView) findViewById(R.id.button_more_columns);
		mViewPager = (ViewPager) findViewById(R.id.mViewPager);

		fm = getSupportFragmentManager();
		title.top_title_text.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent mIntent = new Intent(Const.REFLASH);
				// 发送广播
				sendBroadcast(mIntent);

			}
		});
		askQuestion.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				if (TextUtils.isEmpty(SharedPreferencesKit.getString(InformationActivity.this, Const.SP_KEY_USER_ID))) {
					Intent intent = new Intent(InformationActivity.this, LoginActivity.class);
					startActivity(intent);
				} else {
					Intent intent = new Intent(InformationActivity.this, AskQuestionActivity.class);

					intent.putExtra("userId", "");
					startActivity(intent);
				}
			}
		});
		// askQuestion.setOnTouchListener(new OnTouchListener() {
		//
		// @Override
		// public boolean onTouch(View arg0, MotionEvent event) {
		//
		// final int X = (int) event.getRawX();
		// final int Y = (int) event.getRawY();
		//
		// switch (event.getAction()) {
		// case MotionEvent.ACTION_MOVE:
		//
		// RelativeLayout.LayoutParams layoutParams = new
		// RelativeLayout.LayoutParams(
		// android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
		// android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
		// layoutParams.leftMargin = X - 25;
		// layoutParams.topMargin = Y - 40;
		//
		// if (layoutParams.leftMargin <= 0 || layoutParams.leftMargin >= (width
		// - 50) || layoutParams.topMargin <= 5
		// || layoutParams.topMargin >= (height - 130)) {
		// return true;
		// }
		//
		// askQuestion.setLayoutParams(layoutParams);
		// parent.invalidate();
		//
		// break;
		//
		// case MotionEvent.ACTION_DOWN:
		//
		// break;
		// case MotionEvent.ACTION_UP:
		//
		// break;
		// }
		//
		// return false;
		//
		// }
		// });

		button_more_columns.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				if (TextUtils.isEmpty(SharedPreferencesKit.getString(InformationActivity.this, Const.SP_KEY_USER_ID))) {
					// 如果用户未登录跳转到登录界面
					Intent intent = new Intent(InformationActivity.this, LoginActivity.class);
					tag = 2;
					startActivityForResult(intent, 3);

				} else {
					Intent intent_channel = new Intent(InformationActivity.this, ChannelActivity.class);
					startActivityForResult(intent_channel, CHANNELREQUEST);
				}

			}
		});
		setChangelView();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// setChangelView();
	}

	/**
	 * 当栏目项发生变化时候调用
	 * */
	private void setChangelView() {
		initColumnData();
		initTabColumn();
		initFragment();
	}

	/**
	 * 初始化fragment
	 * 
	 * 
	 * @author lkx Created at 2015-10-3 下午7:27:32
	 */
	private void initFragment() {
		// removeAllFrags(fragments);
		fragments.clear();// 清空
		int count = userChannelList.size();
		for (int i = 0; i < count; i++) {

			Bundle data = new Bundle();
			data.putString("text", userChannelList.get(i).getName());
			data.putString("id", userChannelList.get(i).getId());
			data.putString("sort", userChannelList.get(i).getSort());
			if (userChannelList.get(i).getName().equals("订阅")) {
				SubscriptionFragment frg = new SubscriptionFragment(InformationActivity.this);
				frg.setArguments(data);

				fragments.add(frg);
			} else {
				// frg = new NewsFragment(InformationActivity.this, i);
				CopyOfNewsFragment frg = new CopyOfNewsFragment(InformationActivity.this, i);
				frg.setArguments(data);

				fragments.add(frg);
			}

		}
		if (mAdapetr == null) {
			// mAdapetr = new
			// CopyOfNewsFragmentPagerAdapter(getSupportFragmentManager(),
			// fragments);
			mAdapetr = new NewsFragmentPagerAdapter(getSupportFragmentManager(), fragments);
			mViewPager.setOffscreenPageLimit(0);
			mViewPager.setAdapter(mAdapetr);
			mViewPager.setOnPageChangeListener(pageListener);
			mViewPager.setCurrentItem(0);
			selectTab(0);
		} else {

			mViewPager.setOffscreenPageLimit(0);
			mViewPager.setOnPageChangeListener(pageListener);
			mAdapetr.setFragments(fragments);

			mViewPager.setCurrentItem(0);
			selectTab(0);
		}

	}

	/**
	 * 初始化Column栏目项
	 * 
	 * */
	private void initTabColumn() {
		mRadioGroup_content.removeAllViews();
		int count = userChannelList.size();
		mColumnHorizontalScrollView.setParam(this, mScreenWidth, mRadioGroup_content, ll_more_columns, rl_column);
		for (int i = 0; i < count; i++) {
			// mItemWidth
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			params.leftMargin = 5;
			params.rightMargin = 45;
			TextView columnTextView = new TextView(this);
			columnTextView.setGravity(Gravity.CENTER);
			columnTextView.setTextSize(18.0f);
			columnTextView.setId(i);
			columnTextView.setText(userChannelList.get(i).getName());
			columnTextView.setTextColor(getResources().getColorStateList(R.color.infox_lable_textselect));
			if (columnSelectIndex == i) {
				columnTextView.setSelected(true);
			}
			columnTextView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					for (int i = 0; i < mRadioGroup_content.getChildCount(); i++) {
						View localView = mRadioGroup_content.getChildAt(i);
						if (localView != v)
							localView.setSelected(false);
						else {
							localView.setSelected(true);
							mViewPager.setCurrentItem(i);
						}
					}
					// Toast.makeText(getApplicationContext(),
					// userChannelList.get(v.getId()).getId(),
					// Toast.LENGTH_SHORT).show();
				}
			});
			mRadioGroup_content.addView(columnTextView, i, params);
		}
		if (Const.INTO_GUIDE) {
			intoGuide(0);
		}
	}

	/**
	 * 获取频道数据
	 * 
	 * 
	 * @author lkx Created at 2015-10-15 下午7:36:10
	 */
	private void initColumnData() {

		userChannelList = ((ArrayList<ChannelItem>) ChannelManage.getManage(Application.getInstance().getSQLHelper()).getUserChannel());

	}

	/**
	 * ViewPager切换监听方法
	 * */
	public OnPageChangeListener pageListener = new OnPageChangeListener() {

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int position) {
			mViewPager.setCurrentItem(position);
			selectTab(position);
		}
	};

	/**
	 * 选择的Column里面的Tab
	 * */
	private void selectTab(int tab_postion) {
		columnSelectIndex = tab_postion;
		for (int i = 0; i < mRadioGroup_content.getChildCount(); i++) {
			View checkView = mRadioGroup_content.getChildAt(tab_postion);
			int k = checkView.getMeasuredWidth();
			int l = checkView.getLeft();
			int i2 = l + k / 2 - mScreenWidth / 2;
			// rg_nav_content.getParent()).smoothScrollTo(i2, 0);
			mColumnHorizontalScrollView.smoothScrollTo(i2, 0);
			// mColumnHorizontalScrollView.smoothScrollTo((position - 2) *
			// mItemWidth , 0);
		}
		// 判断是否选中
		for (int j = 0; j < mRadioGroup_content.getChildCount(); j++) {
			View checkView = mRadioGroup_content.getChildAt(j);
			boolean ischeck;
			if (j == tab_postion) {
				ischeck = true;
			} else {
				ischeck = false;
			}
			checkView.setSelected(ischeck);
		}
	}

	public void exit() {
		if ((System.currentTimeMillis() - exitTime) > 2000) {
			Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
			exitTime = System.currentTimeMillis();
		} else {
			finish();
			Application.getInstance().exit();
			System.exit(0);
		}
	}

	@Override
	public void onBackPressed() {
		exit();

	}

	@Override
	protected void onDestroy() {
		InformationActivity.this.unregisterReceiver(receiveBroadCast);
		super.onDestroy();
	}

	@Override
	public void onShowcaseViewHide(ShowcaseView showcaseView) {
		step++;
		intoGuide(-1);
	}

	@Override
	public void onShowcaseViewDidHide(ShowcaseView showcaseView) {

	}

	@Override
	public void onShowcaseViewShow(ShowcaseView showcaseView) {

	}

	public class ChangeBroadcast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// 得到数据变化的广播
			if (intent.getAction().equals(Const.CHANGECOUNT)) {
				if (Const.UNREADMESSAGE != 0) {
					title.messagenumber.setText(Const.UNREADMESSAGE + "");
					title.messagenumber.setVisibility(View.VISIBLE);
				} else {
					title.messagenumber.setVisibility(View.GONE);
				}

			}

		}

	}

	public void removeAllFrags(List<Fragment> list) {

		for (int i = list.size(); i < list.size(); i--) {

			list.remove(i);
		}
	}
}
